package com.situ.car.controller;

import com.situ.car.pojo.entity.User;
import com.situ.car.service.IUserService;
import com.situ.car.service.Impl.UserServiceImpl;
import com.situ.car.util.*;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

@WebServlet("/user")
public class UserController extends BaseController{
    private IUserService userService = new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("UserController.service");
        String method = req.getParameter("method");
        switch (method) {
            case "login":
                login(req, resp);
                break;
            case "register":
                register(req, resp);
                break;
            case "logout":
                logout(req, resp);
                break;
            case "selectByInfoId":
                selectByInfoId(req, resp);
                break;
            case "updateInfo":
                updateInfo(req, resp);
                break;
            case "selectAccount":
                selectAccount(req, resp);
                break;
            case "updatePassword":
                updatePassword(req, resp);
                break;
        }
    }

    private void register(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.register");
        User user = MyBeanUtils.copyToBean(req, User.class);
        Integer accountCount = userService.selectByAccount(user);
        if (accountCount == 0) {
            userService.register(user);
            toJSON(resp, Result.ok("注册成功！"));
        } else {
            toJSON(resp, Result.error("账号已经存在！"));
        }
    }

    private void updatePassword(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.updatePassword");
        String id = req.getParameter("id");
        User user = userService.selectPassword(Integer.parseInt(id));
        String password = req.getParameter("password");
        String newPassword = req.getParameter("newPassword");
        System.out.println(user);
        System.out.println(user.getPassword());
        System.out.println(password);
        if (Objects.equals(user.getPassword(), password)) {
            userService.updatePassword(Integer.parseInt(id), newPassword);
            toJSON(resp, Result.ok("修改成功！请重新登录"));
            HttpSession session = req.getSession();
            session.removeAttribute("user");
            Cookie cookie = CookieUtils.getCookie(req, "autoLogin");
            //如果用户没有勾选自动登录，那么这个Cookie就是null，回报空指针异常，所以要加判断
            if (cookie != null) {
                //设置Cookie的存活时间为0
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
        } else {
            toJSON(resp, Result.error("原密码错误！"));
        }
    }

    private void selectAccount(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.selectAccount");
        String id = req.getParameter("id");
        User user = userService.selectAccount(Integer.parseInt(id));
        toJSON(resp, Result.ok(user));
    }

    private void updateInfo(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.updateInfo");
        User user = MyBeanUtils.copyToBean(req, User.class);
        int userPD = userService.updateInfo(user);
        System.out.println(userPD);
        HttpSession session = req.getSession();
        if (userPD != 0) {
            toJSON(resp, Result.ok("修改成功！"));
            session.setAttribute("user", user);
        } else {
            toJSON(resp, Result.error("账号已经存在！"));
        }
    }

    private void selectByInfoId(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.selectByInfoId");
        String id = req.getParameter("id");
        User user = userService.selectByInfoId(Integer.parseInt(id));
        toJSON(resp, Result.ok(user));
    }
    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserController.logout");
        HttpSession session = req.getSession();
        session.removeAttribute("user");

        Cookie cookie = CookieUtils.getCookie(req, "autoLogin");
        //如果用户没有勾选自动登录，那么这个Cookie就是null，回报空指针异常，所以要加判断
        if (cookie != null) {
            //设置Cookie的存活时间为0
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
        }

        toJSON(resp, Result.ok("退出成功"));
//        resp.sendRedirect("/page/login");
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.login");
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {
            toJSON(resp, Result.error("验证码错误"));
            return;
        }
        User user = userService.login(account, password);
        if (user == null) {
            JSONUtil.toJSON(resp, Result.error("用户名或密码错误"));
        }
        if (user.getStatus() == 0) {
            toJSON(resp, Result.error("该用户已经禁用，请联系管理员"));
            return;
        }
        //自动登录
        String autoLogin = req.getParameter("autoLogin");
        if (!ObjectUtils.isEmpty(autoLogin)) {
            Cookie cookie = new Cookie("autoLogin", user.getAccount() + "&" + user.getPassword());
            //设置Cookie 的存活时间和绑定路径
            cookie.setMaxAge(60*60*24*7);//设置时间为1周
            cookie.setPath(req.getContextPath());
            //在响应resp中添加cookie，返回给浏览器
            resp.addCookie(cookie);
        }
        session.setAttribute("user", user);
        toJSON(resp, Result.ok("登录成功"));
    }

}
